package cl.query.web.servlet;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import cl.extractor.VehicleExtractor;
import cl.model.dto.Region;
import cl.model.dto.Vehicle;
import cl.util.DataService;


/**
 * Servlet implementation class CreaQueryServlet
 */
public class GetVehiclesByRegionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger log = Logger.getLogger(GetVehiclesByRegionServlet.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetVehiclesByRegionServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String idRegion = request.getParameter("idRegion");
		Region region = DataService.getInstance().getRegion(idRegion);
	
		VehicleExtractor ve = new VehicleExtractor();
		
		for(Iterator<Vehicle> it = region.getVehicles().iterator(); it.hasNext();){
			Vehicle vehicle = (Vehicle)it.next();
			ve.extract("http://www2.chileautos.cl/auto.asp?codauto="+vehicle.getCodigoVehiculo(), vehicle);
			DataService.getInstance().actualizarVehicle(vehicle);
		}
		
		ServletOutputStream salida = response.getOutputStream();
		salida.println(region.getVehicles().size());
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
}
